<template>
	<view class="">
		<view class="cu-modal " :class="isShowAuth ? 'show' : ''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">用户授权登录</view>
					<view class="action" @tap="hideAuthModal"><text class="cuIcon-close text-red"></text></view>
				</view>
				<view class="padding-xl">
					<view class="cu-steps">
						<view class="cu-item" :class="index > num ? '' : 'text-blue'" v-for="(item, index) in numList"
							:key="index">
							<text class="num" :data-index="index + 1"></text>
							{{ item.name }}
						</view>
					</view>
					<button v-if="!authUserInfo" style="width: 100%;" class="cu-btn block bg-main margin-tb-sm lg" open-type="getUserInfo"
						@getuserinfo="mpGetUserInfo">用户信息授权</button>
					<button v-if="showMobileBtn && !customerMobile" style="width: 100%;" class="cu-btn block bg-main margin-tb-sm lg"
						open-type="getPhoneNumber" @getphonenumber="mpGetUserMobile">
						授权手机号
					</button>
					<button class="cu-btn block bg-blue margin-tb-sm lg" style="width: 100%;" v-if="authUserInfo && authMobile">
						<text class="cuIcon-loading2 cuIconfont-spin"></text>
						验证中
					</button>
					<view class="" v-show="customerMobile">
						<view class="cu-form-group">
							<view class="title">手机号</view>
							<input placeholder="输入手机号" type="number" v-model="phone" />
						</view>
						<view class="cu-form-group">
							<view class="title">验证码</view>
							<input placeholder="输入验证码" type="number" v-model="vcode" />
							<button class="cu-btn bg-green shadow" @click="getVcode()">{{ codeText }}</button>
						</view>
						<button class="cu-btn block bg-main margin-tb-sm lg" @click="loginUser">验证手机号</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				num: -1,
				numList: [{
						name: '授权用户信息'
					},
					{
						name: '授权手机号'
					},
					{
						name: '验证信息'
					}
				],
				isShowAuth:false,
				authUserInfo: false,
				userInfo: {},
				showMobileBtn: false,
				showMobileInput: false,
				authMobile: false,
				mobileInfo: {},
				customerMobile: false,
				time: 0,
				codeText: '验证码',
				interval: null,
				phone: '',
				vcode: '',
				countryCode: '+86'
			};
		},
		name: 'auth',
		props: {
			showAuth: {
				type: Boolean,
				default: true
			}
		},
		async mounted() {
			console.log('mounted,onload in..');
			let token = uni.getStorageSync('token');
			if (!token)
				await this.wxlogin();
		},
		watch: {
			async showAuth(newValue, oldValue) {
				// this.isShowAuth = newValue
				// console.log('showAuth===>newValue:' + newValue + ',oldValue:' + oldValue);
				// if (newValue) {
				// 	await this.wxlogin();
				// }
			}
		},
		methods: {
			async wxlogin() {
				let res = await uni.login({
					provider: 'weixin'
				});
				console.log('wxlogin,onload in..', res, res[1]['code']);
				if (res[1]['code']) {
					let code = res[1]['code'];
					uni.setStorageSync('sessionCode', code);
					console.log('code', code);
					let res1 = await this.$request.post(this.$requestUrl.JSCONDE2_SESSION_URL, {
						data: {
							jscode: code
						}
					});
					console.log(res1);
					if (res1 && res1.token && res1.userInfo) {
						this.isShowAuth = false
						this.$emit('update:showAuth', this.isShowAuth)
						this.$emit('update:auth', true) //告诉父组件，已经授权成功
						uni.setStorageSync('token', res1.token);
						uni.setStorageSync('organization', res1.userInfo.organization);
						uni.setStorageSync('userId', res1.userId);
						uni.setStorageSync('mobile', res1.userInfo.mobile);
						uni.setStorageSync('userInfo', res1.userInfo);
						uni.setStorageSync('org', res1.userInfo.organization)
					} else if (res1 && res1.session3rd) {
						this.isShowAuth = true
						uni.setStorageSync('session3rd', res1.session3rd);
						uni.setStorageSync('openid', res1.openid);
					} else {
						this.isShowAuth = true
					}
				}
			},
			async decodeWechat(encryptedData, iv) {
				let session3rd = uni.getStorageSync('session3rd');
				if (!session3rd) {
					await this.wxlogin()
				}
				let res = await this.$request.post(this.$requestUrl.DECODE_WECHAT_URL, {
					data: {
						session3rd: session3rd,
						encryptedData,
						iv
					}
				});
				return res;
			},
			hideAuthModal() {
				this.isShowAuth = false;
				this.$emit('update:showAuth', this.isShowAuth) //告诉父组件，已经授权成功
				console.log('update:showAuth', this.isShowAuth)
			},
			async mpGetUserInfo(result) {
				console.log('mpGetUserInfo', result);
				if (result.detail.errMsg !== 'getUserInfo:ok') {
					uni.showModal({
						title: '获取用户信息失败',
						content: '请重新点击授权按钮',
						showCancel: false
					});
					return false;
				} else {
					let rs = await this.decodeWechat(result.detail.encryptedData, result.detail.iv);
					console.log('rs', rs, this.auth);
					if (rs && rs.token && rs.userInfo) {
						this.isShowAuth = false
						this.$emit('update:showAuth', this.isShowAuth)
						this.$emit('update:auth', true) //告诉父组件，已经授权成功
						uni.setStorageSync('token', rs.token);
						uni.setStorageSync('userId', rs.userId);
						uni.setStorageSync('mobile', rs.userInfo.mobile);
						uni.setStorageSync('userInfo', rs.userInfo);
						uni.setStorageSync('organization', rs.userInfo.organization);
						uni.setStorageSync('org', rs.userInfo.organization)
					} else if (rs.openId) {
						this.userInfo = rs;
						this.authUserInfo = true;
						this.showMobileBtn = true;
						this.num = 0;
					} else if (rs.status == 'failSeesionKey') {
						await this.wxlogin();
						uni.showToast({
							icon: 'none',
							title: '网络异常，请重试'
						});
					} else if (rs.status == 'failDecryptData') {
						await this.wxlogin();
						uni.showToast({
							icon: 'none',
							title: '网络异常，请重试'
						});
					}
				}
			},
			async mpGetUserMobile(result) {
				console.log('mpGetUserMobile', result);
				if (result.detail.errMsg !== 'getPhoneNumber:ok') {
					this.customerMobile = true;
					return false;
				} else {
					let rs = await this.decodeWechat(result.detail.encryptedData, result.detail.iv);
					console.log('rs', rs);
					if (rs && rs.phoneNumber) {
						this.showMobileBtn = false;
						this.customerMobile = false;
						this.authMobile = false;
						this.mobileInfo = rs;
						this.num = 1;
						this.countryCode = '+' + rs.countryCode
						this.loginUser();
					} else if (rs.status == 'failSeesionKey') {
						this.wxlogin();
						uni.showToast({
							icon: 'none',
							title: '网络异常，请重试'
						});
					} else if (rs.status == 'failDecryptData') {
						this.wxlogin();
						uni.showToast({
							icon: 'none',
							title: '网络异常，请重试'
						});
					}
				}
			},
			async getVcode() {
				let that = this;
				console.log(that.time);
				if (that.time == 0 && that.phone) {
					let res = await this.$request.post(this.$requestUrl.SEND_SMS_URL, {
						data: {
							phone: that.phone,
							countryCode: that.countryCode
						}
					});
					if (res.code == 200) {
						uni.showToast({
							title: '验证码发送成功',
							icon: 'none'
						});
						that.time = 60;
						this.interval = setInterval(function() {
							if (that.time > 0) {
								that.time = that.time - 1;
								that.codeText = that.time + '(S)';
							} else if (that.time <= 0) {
								that.time = 0;
								that.codeText = '验证码';
								clearInterval(that.interval);
							}
						}, 1000);
					} else {
						uni.showToast({
							title: '验证码发送失败',
							icon: 'none'
						});
					}
				} else {
					return;
				}
			},
			async loginUser() {
				let that = this;
				let res = await this.$request.post(this.$requestUrl.AUTH_WECHAT_LOGIN_URL, {
					data: {
						userInfo:that.userInfo,
						mobileInfo:that.mobileInfo,
						mobile: that.phone,
						captcha: that.vcode,
						countryCode: that.countryCode
					}
				});
				if (res && res.token && res.userInfo) {
					that.isShowAuth = false
					that.num = 2;
					that.$emit('update:auth', true) //告诉父组件，已经授权成功
					that.$emit('update:showAuth', that.isShowAuth)
					uni.setStorageSync('token', res.token);
					uni.setStorageSync('userId', res.userId);
					uni.setStorageSync('mobile', res.userInfo.mobile);
					uni.setStorageSync('userInfo', res.userInfo);
					uni.setStorageSync('organization', res.userInfo.organization);
					uni.setStorageSync('org', res.userInfo.organization)
				}
			}
		}
	};
</script>

<style>
	.content {
		background-color: #FFFFFF;
	}
</style>
